package JDBC;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class BaseDB {
    static final String DRIVER = "oracle.jdbc.driver.OracleDriver";
    static final String URL = "jdbc:oracle:thin:@localhost:1521:orcl";
    static final String USER = "scott";
    static final String PASS = "tiger";

    /**
     * 获得Connection
     *
     * @return
     */
    public static Connection getConn() {
        Connection conn = null;
        try {
            Class.forName(DRIVER);
            conn = DriverManager.getConnection(URL, USER, PASS);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 增删改
     *
     * @param sql
     * @throws SQLException
     */
    public static void updateSql(String sql) throws SQLException {
        Connection conn = getConn();
        Statement st = conn.createStatement();
        st.executeUpdate(sql);
        closeAll(conn, st, null);
    }


    /**
     * 预编译增删改
     *
     * @param sql
     * @param arr
     */
    public static void updateSql2(String sql, Object[] arr) {
        Connection conn = getConn();
        PreparedStatement psmt = null;
        try {
            psmt = conn.prepareStatement(sql);
            setZhan(psmt,arr);
            psmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeAll(conn, psmt, null);
        }

    }


    /**
     * 设置占位符参数
     * @param psmt
     * @param arr
     */
    public static void setZhan(PreparedStatement psmt, Object[] arr) {
        if (psmt == null)
            return;
        try {
            for (int i = 1; i <= arr.length; i++) {
                psmt.setObject(i, arr[i - 1]);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    /**
     * 关闭Connection和Statement ResultSet
     *
     * @param conn
     * @param st
     */
    public static void closeAll(Connection conn, Statement st, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (st != null) {
                st.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
